﻿using System;
using System.Net;
using System.Web;
using Bricks.Injecting;
using Bricks.Security;

namespace Motar.Web.Mvc
{
    
    /// <summary>
    /// 
    /// </summary>
    public class FilterIPAddressAttribute : AuthorizeAttributeBase
    {

        /// <summary>
        /// 
        /// </summary>
        private readonly IValueResolver<IIPAddressFilterFacade> _resolver;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="resolver"></param>
        public FilterIPAddressAttribute(IValueResolver<IIPAddressFilterFacade> resolver)
        {
            if (resolver == null)
            {
                throw new ArgumentNullException("resolver");
            }
            _resolver = resolver;
        }

        /// <summary>
        /// 
        /// </summary>
        public FilterIPAddressAttribute() :
            this(new SingleValueResolver<IIPAddressFilterFacade, NullIPAddressFilterFacade>())
        {
        }

        /// <summary>
        /// 
        /// </summary>
        protected IValueResolver<IIPAddressFilterFacade> Resolver
        {
            get { return _resolver; }
        }

        /// <summary>
        /// 
        /// </summary>
        public virtual string Key { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool Authorize(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }

            IPAddress address;

            if(IPAddress.TryParse(httpContext.Request.UserHostAddress, out address))
            {
                return string.IsNullOrEmpty(Key) ? Resolver.Resolve().Grant(address) : Resolver.Resolve().Grant(address, Key);
            }
            else
            {
                return false;
            }
        }
    }
}
